package com.snifferx.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MessageDigestUtil {
	private static MessageDigestUtil messageDigestUtilInstance;

	public synchronized String encrypt(String plaintext) throws Exception {
		String digest = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] hash = md.digest(plaintext.getBytes("UTF-8"));

			// converting byte array to Hexadecimal String
			StringBuilder sb = new StringBuilder(2 * hash.length);
			for (byte b : hash) {
				sb.append(String.format("%02x", b & 0xff));
			}

			digest = sb.toString();

		} catch (UnsupportedEncodingException ex) {
			ex.printStackTrace();
		} catch (NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}
		return digest;
	}

	public static synchronized MessageDigestUtil getInstance() {
		if (messageDigestUtilInstance == null) {
			messageDigestUtilInstance = new MessageDigestUtil();
		}
		return messageDigestUtilInstance;
	}

	public static void main(String[] args) {
		try {
			MessageDigestUtil messageDigestUtil = getInstance();
			messageDigestUtil.testEncrypt();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void testEncrypt() throws Exception {
		MessageDigestUtil messageDigestUtil = getInstance();
		String encrypted = messageDigestUtil.encrypt("admin");

		System.out.println("encrypted: " + encrypted);
	}
}